//
// Radix Sort
// Created by Win10 on 2023/4/8.
//

#ifndef C_DATA_STRUCTURE_RADIX_SORT_H
#define C_DATA_STRUCTURE_RADIX_SORT_H


#include <algorithm>
template<typename T>
// A utility function to get maximum value in arr[]
T getMax(T a[], int len)
{
  T mx = a[0];
  for (int i = 1; i < len; i++)
    if (a[i] > mx)
      mx = a[i];
  return mx;
}

template<typename T>
// A function to do counting sort of arr[] according to
// the digit represented by exp.
void countSort(T a[], int len, int exp)
{
  T output[len]; // output array
  int i, count[10] = { 0 };

  // Store count of occurrences in count[]
  for (i = 0; i < len; i++)
    count[(a[i] / exp) % 10]++;

  // Change count[i] so that count[i] now contains actual
  //  position of this digit in output[]
  for (i = 1; i < 10; i++)
    count[i] += count[i - 1];

  // Build the output array
  for (i = len - 1; i >= 0; i--) {
    output[count[(a[i] / exp) % 10] - 1] = a[i];
    count[(a[i] / exp) % 10]--;
  }

  // Copy the output array to arr[], so that arr[] now
  // contains sorted numbers according to current digit
  for (i = 0; i < len; i++)
    a[i] = output[i];
}

template<typename T>
//LSD（Least Significant Digit first）
void radix_sort(T a[], int len) {
  // Find the maximum number to know number of digits
  int m = getMax(a, len);

  // Do counting sort for every digit. Note that instead
  // of passing digit number, exp is passed. exp is 10^i
  // where i is current digit number
  for (int exp = 1; m / exp > 0; exp *= 10)
    countSort(a, len, exp);
}

#endif //C_DATA_STRUCTURE_RADIX_SORT_H
